import { defineStore } from 'pinia'
import { ref } from 'vue'
import { api, UserInfo } from '@/services/api'
import type { LoginRequest, RegisterRequest } from '@/services/api'

interface LoginResponse {
  token: string
  userInfo: UserInfo
}

export const useAuthStore = defineStore('auth', () => {
  const user = ref<UserInfo | null>(null)
  const token = ref<string | null>(null)
  const loading = ref(false)

  const login = async (username: string, password: string, remember: boolean = false) => {
    loading.value = true
    try {
      const loginData: LoginRequest = { username, password }
      const response = await api.login(loginData) as LoginResponse
      
      token.value = response.token
      user.value = response.userInfo
      
      if (remember) {
        localStorage.setItem('token', response.token)
        localStorage.setItem('user', JSON.stringify(response.userInfo))
      } else {
        sessionStorage.setItem('token', response.token)
        sessionStorage.setItem('user', JSON.stringify(response.userInfo))
      }
      
      return true
    } catch (error) {
      console.error('Login failed:', error)
      return false
    } finally {
      loading.value = false
    }
  }

  const register = async (data: RegisterRequest) => {
    loading.value = true
    try {
      const userInfo = await api.register(data)
      return await login(data.username, data.password)
    } catch (error) {
      console.error('Register failed:', error)
      return false
    } finally {
      loading.value = false
    }
  }

  const logout = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('user')
  }

  const initialize = () => {
    let savedToken = sessionStorage.getItem('token')
    let savedUser = sessionStorage.getItem('user')
    
    if (!savedToken || !savedUser) {
      savedToken = localStorage.getItem('token')
      savedUser = localStorage.getItem('user')
    }
    
    if (savedToken && savedUser) {
      token.value = savedToken
      user.value = JSON.parse(savedUser)
    }
  }

  return {
    user,
    token,
    loading,
    login,
    register,
    logout,
    initialize
  }
}) 